#include <Arduino.h>
#include "button.h"

const int wdtTimeout = 10000;  //time in ms to trigger the watchdog
hw_timer_t *timer    = NULL;

void feed_dog(void)
{
  timerWrite(timer,0);
  //Serial.println("feed_dog success");
}

void IRAM_ATTR resetModule() 
{
  ets_printf("ESP32 HEAP1 %d\r\n", esp_get_free_heap_size());
  ets_printf("reboot\n");
  esp_restart();
}

void setup() 
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);

  Serial.printf("ESP32 HEAP %d\r\n", esp_get_free_heap_size());

  button_Init();//按键初始化

  Serial.printf("ESP32 HEAP %d\r\n", esp_get_free_heap_size());

  timer = timerBegin(0, 80, true);                  //timer 0, div 80
  timerAttachInterrupt(timer, &resetModule, true);  //attach callback
  timerAlarmWrite(timer, wdtTimeout * 1000, false); //set time in us
  timerAlarmEnable(timer);                          //enable interrupt

  Serial.printf("loop start\r\n");
}

void loop() 
{
  // put your main code here, to run repeatedly:
  //uint8_t menu_event = MENU_EVENT_NULL;

  // timerWrite(timer, 0); //reset timer (feed watchdog)
  feed_dog();
 
  uint8_t button_state = get_button_state();
  if(button_state != 0)
  {
    Serial.printf("ESP32 HEAP1 %d\r\n", esp_get_free_heap_size());
    Serial.printf("button %d\r\n", button_state);
  }

  feed_dog();
  //timerWrite(timer, 0); //reset timer (feed watchdog)
}